package com.toman.ui.data.report;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.mikephil.charting.components.AxisBase;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.toman.Adpter.ItemListAdapter;
import com.toman.Interfaces.NewBaseUrl;
import com.toman.R;
import com.toman.Util.CircleTransform;
import com.toman.Util.IntentUtils;
import com.toman.Util.SPUtils;
import com.toman.Util.StringUtils;
import com.toman.Util.ToastUtil;
import com.toman.Util.ViewUtil;
import com.toman.bean.DataBean;
import com.toman.bean.ItemDataBean;
import com.toman.toolbar.ToolBarActivity;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.squareup.picasso.Picasso;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import okhttp3.Response;
import tbsplus.tbs.tencent.com.tbsplus.TbsPlus;

public class DataCompanyActivity extends ToolBarActivity {
    ItemListAdapter adapterData;

    CommonAdapter<ItemDataBean> adapter;
    CommonAdapter<ItemDataBean> adapterChart;
    @BindView(R.id.tv_data)
    TextView tvData;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_status)
    ImageView ivStatus;
    @BindView(R.id.lineChart)
    LineChart lineChart;
    @BindView(R.id.rl_base)
    RelativeLayout rlBase;
    @BindView(R.id.gv_data)
    RecyclerView gvData;
    @BindView(R.id.lv)
    RecyclerView lv;
    String companyId;
    Intent intent;
    @BindView(R.id.tv_title_line)
    TextView tvTitleLine;
    private List<ItemDataBean> listChart = new ArrayList<>();
    private List<ItemDataBean> listTitle = new ArrayList<>();
    DataBean dataBean;
    Boolean isFirst = true;
    private String urlDp;
    private String urlAppindex;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_data_company);
        ButterKnife.bind(this);
        initView();
    }

    @Override
    public void onResume() {
        super.onResume();
        get();
    }

    private void initView() {
        urlAppindex = "https://www.zjtmcloud.com:8090/appindex?index=";
        urlDp = "https://www.zjtmcloud.com:8090/appdp?id=";
//        urlAppindex="http://192.168.70.122:8005/appindex?index=";
//        urlDp="http://192.168.70.122:8005/appdp?id=";
        intent = getIntent();
        companyId = intent.getStringExtra("id");
        initToolBar(intent.getStringExtra("msg"));

        adapter = new CommonAdapter<ItemDataBean>(this, R.layout.item_data, listTitle) {
            @Override
            protected void convert(ViewHolder holder, ItemDataBean item, int position) {
                holder.setText(R.id.tv_name, item.getTitle());
                holder.setText(R.id.tv_data, item.getData());
                if (position == listTitle.size() - 1) {
                    holder.getView(R.id.iv_line).setVisibility(View.GONE);
                }
            }
        };
        adapterChart = new CommonAdapter<ItemDataBean>(this, R.layout.item_chart, listChart) {
            @Override
            protected void convert(ViewHolder holder, ItemDataBean item, int position) {
                int[] status = {R.mipmap.data_icon_rise, R.mipmap.data_icon_decline, R.mipmap.data_icon_fair};
                holder.setText(R.id.tv_name, item.getTitle());
                holder.setText(R.id.tv_data, item.getData());
                ImageView iv = holder.getView(R.id.iv_icon);
                if (!StringUtils.isEmpty(item.getIcon())) {
                    Picasso.with(getApplicationContext()).load(item.getIcon()).error(R.mipmap.my_icon_head).transform(new CircleTransform()).into(iv);

                }
//                iv.setImageResource(R.mipmap.account);
                if (item.getDataStatus() != 3) {
                    try {
                        holder.setImageResource(R.id.iv_status, status[item.getDataStatus()]);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    holder.getView(R.id.iv_status).setVisibility(View.GONE);

                }
            }
        };
        adapterChart.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<ItemDataBean> list = adapterChart.getDatas();

                ItemDataBean bean = list.get(position);
                if (StringUtils.isEmpty(bean.getType())){
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("html", urlDp + companyId + "&index=" + bean.getType()+ "&token=" + token);
//                bundle.putString("html", " http://192.168.70.122:8005/appdp?id=" + companyId + "&index=" + bean.getType());
                IntentUtils.startActivity(DataCompanyActivity.this, X5Activity.class, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                List<ItemDataBean> list = adapter.getDatas();
                ItemDataBean bean = list.get(position);
                if (StringUtils.isEmpty(bean.getType())){
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("html", urlDp + companyId + "&index=" + bean.getType()+ "&token=" + token);
//                String url = "http://www.zjtmcloud.com/appdp?id=" + companyId + "&index=" + bean.getType()+"&token=" + token;
//
//                TbsPlus.openUrl(DataCompanyActivity.this, url, TbsPlus.eTBSPLUS_SCREENDIR. eTBSPLUS_SCREENDIR_LANDSCAPE);
//                bundle.putString("html", " http://192.168.70.122:8005/appdp?id=" + companyId + "&index=" + bean.getType()
                IntentUtils.startActivity(DataCompanyActivity.this, X5Activity.class, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        gvData.setAdapter(adapter);
        lv.setAdapter(adapterChart);
        DividerItemDecoration itemDecoration2 = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        itemDecoration2.setDrawable(getResources().getDrawable(R.drawable.ll_diver_vertical_none));
        if (isFirst) {
            isFirst = false;
            lv.addItemDecoration(itemDecoration2);
        }

    }

    private void initList() {
//        String items[] = new String[]{"接入产线数", "当日总产量", "当月总产量"};
//        for (int i = 0; i < items.length; i++) {
//            ItemDataBean bean = new ItemDataBean();
//            bean.setTitle(items[i]);
//            bean.setData(i + "00");
//            listChart.add(bean);
//        }
        initView();
        GridLayoutManager mgr = new GridLayoutManager(this, listTitle.size());
        LinearLayoutManager manager = new LinearLayoutManager(this);

        gvData.setLayoutManager(mgr);
        lv.setLayoutManager(manager);
        adapterChart.notifyDataSetChanged();
        adapter.notifyDataSetChanged();

    }

    private void initLine() {
        lineChart.setDrawGridBackground(false);
        lineChart.setNoDataTextColor(getResources().getColor(R.color.white));
        lineChart.setBorderColor(getResources().getColor(R.color.transparent));
        // no description text
        lineChart.getDescription().setEnabled(false);

        //设置显示类型，LINE CIRCLE SQUARE EM
        // enable touch gestures
        lineChart.setTouchEnabled(true);

        // enable scaling and dragging
        lineChart.setDragEnabled(false);
        lineChart.setScaleEnabled(false);
        // mChart.setScaleXEnabled(true);
        // mChart.setScaleYEnabled(true);
        lineChart.getAxisRight().setEnabled(false);
        lineChart.getAxisLeft().setEnabled(false);
        ;
        lineChart.setDrawGridBackground(false);


        // if disabled, scaling can be done on x- and y-axis separately
        lineChart.setPinchZoom(true);
    }

    public void line(String[] name, float[] content, String label) {
        initLine();


        ArrayList<Entry> yVals1 = new ArrayList<Entry>();
        for (int i = 0; i < content.length; i++) {
            if (i == content.length - 1) {
                yVals1.add(new Entry(i, content[i], getResources().getDrawable(R.drawable.circle_blue)));

            } else {
                yVals1.add(new Entry(i, content[i]));
            }
        }
        for (int i = 0; i < name.length; i++) {
            name[i] = name[i] + "月";
        }


//        int ssmax = (int) max;
        try {
            lineChart.setVisibility(View.VISIBLE);
            LineDataSet set1, set2, set3;

            if (lineChart.getData() != null &&
                    lineChart.getData().getDataSetCount() > 0) {
                set1 = (LineDataSet) lineChart.getData().getDataSetByIndex(0);

                set1.setValues(yVals1);

//                set1.setLabel("（" + label + "）");


                LabelFormatter labelFormatter = new LabelFormatter(name);
                XAxis xAxis = lineChart.getXAxis();
                xAxis.setTextColor(Color.WHITE);
//                xAxis.setLabelCount(str.length, true);

                xAxis.setValueFormatter(labelFormatter);
                lineChart.getData().notifyDataChanged();
                lineChart.notifyDataSetChanged();
                lineChart.animateXY(1000, 1000);

            } else {
                // create a dataset and give it a type
                set1 = new LineDataSet(yVals1, "");

                set1.setAxisDependency(YAxis.AxisDependency.LEFT);
                set1.setColor(ColorTemplate.getHoloBlue());
                set1.setCircleColor(ColorTemplate.getHoloBlue());
//                set1.setLineWidth(2f);
//                set1.setCircleRadius(3f);
//                set1.setFillAlpha(65);
                set1.setFillColor(Color.WHITE);
                set1.setHighLightColor(Color.rgb(244, 117, 117));
                set1.setDrawCircleHole(false);
                set1.setDrawCircles(true);
                set1.setColor(Color.WHITE);
                set1.setLineWidth(1.75f);
                set1.setCircleRadius(5f);
                set1.setCircleHoleRadius(2.5f);
                set1.setColor(Color.WHITE);
                set1.setCircleColor(Color.WHITE);
                set1.setValueTextColor(Color.WHITE);
                set1.setHighLightColor(Color.WHITE);
                set1.setDrawValues(false);
                set1.setMode(LineDataSet.Mode.HORIZONTAL_BEZIER);

                //set1.setFillFormatter(new MyFillFormatter(0f));
                //set1.setDrawHorizontalHighlightIndicator(false);
                //set1.setVisible(false);
                //set1.setCircleHoleColor(Color.WHITE);

                // create a dataset and give it a type
                set1.setDrawValues(true);

                XAxis xAxis = lineChart.getXAxis();
                xAxis.setTextColor(Color.WHITE);
                xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
                xAxis.setLabelCount(content.length - 1, false);

                xAxis.setDrawLabels(true);
                LabelFormatter labelFormatter = new LabelFormatter(name);
                xAxis.setValueFormatter(labelFormatter);

                // create a data object with the datasets
                LineData data = new LineData(set1);
                data.setValueTextColor(Color.WHITE);
                data.setValueTextSize(9f);
                // set data
                lineChart.setData(data);
                lineChart.animateXY(1000, 1000);

            }


        } catch (Exception e) {
        }
    }

    private void setOeeImg(DataBean bean) {
        switch (bean.getOee().getDataStatus()) {
            case 0:
                ivStatus.setImageResource(R.mipmap.data_icon_oee_rise);
                break;
            case 1:
                ivStatus.setImageResource(R.mipmap.data_icon_oee_decline);
                break;
            case 2:
                ivStatus.setImageResource(R.mipmap.data_icon_oee_fair);
                break;
            case 3:
                ivStatus.setVisibility(View.GONE);
                break;
        }
    }

    public void get() {
        String token = (String) SPUtils.get(this, "token", "");
        OkHttpUtils
                .get(NewBaseUrl.indexData)
                .params("token", token)
                .params("companyId", companyId)
                .execute(new StringCallback() {
                    @Override
                    public void onResponse(boolean isFromCache, String result, Request request, @Nullable Response response) {
                        Log.i("test", "数据详情: " + result);
                        JSONObject jsonObj = JSON.parseObject(result);
                        int code = jsonObj.getInteger("code");ViewUtil.lagout(code,getApplicationContext());
                        if (code == 0) {
                            dataBean = (DataBean) JSON.parseObject(jsonObj.getString("data"), DataBean.class);
                            tvData.setText(dataBean.getOee().getData());
                            tvTitle.setText(dataBean.getOee().getTitle());
                            setOeeImg(dataBean);
                            listTitle = dataBean.getTitleList();
                            listChart = dataBean.getChartList();

                            String[] name = dataBean.getLineChart().getX().split(",");
                            String[] content1 = (dataBean.getLineChart().getY().split(","));
                            float[] content = new float[content1.length];
                            for (int i = 0; i < content1.length; i++) {
                                content[i] = Float.parseFloat(content1[i]);
                            }
                            tvTitleLine.setText(dataBean.getLineChart().getName());
                            line(name, content, dataBean.getLineChart().getName());
                            initList();

                        } else {
                            ToastUtil.error(getApplicationContext(), jsonObj.getString("msg"));
                        }

                    }
                });
    }

    @OnClick(R.id.tv_data)
    public void onViewClicked() {
        if (StringUtils.isEmpty(dataBean.getOee().getType())){
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString("html", urlAppindex + companyId + "&index=" + dataBean.getOee().getType()+ "&token=" + token);
//        bundle.putString("html", "http://192.168.70.122:8005/appdp?id=" + companyId + "&index=" +dataBean.getOee().getType());

        IntentUtils.startActivity(DataCompanyActivity.this, X5Activity.class, bundle);

    }
    class LabelFormatter implements IAxisValueFormatter {
        private final String[] mLabels;

        public LabelFormatter(String[] labels) {
            mLabels = labels;
        }

        @Override
        public String getFormattedValue(float value, AxisBase axis) {
            try {
                return mLabels[(int) value];
            } catch (Exception e) {
                e.printStackTrace();
                return mLabels[0];
            }

        }
    }
}
